const app = getApp()

Page({
  data: {
    poetryList: [],
    searchText: '',
    selectedDynasty: '',
    loading: true,
    hasMore: true
  },

  onLoad(options) {
    // 初始化诗词列表
    this.loadPoetryData()
  },

  // 返回上一页
  navigateBack() {
    wx.navigateBack()
  },

  // 加载诗词数据
  loadPoetryData() {
    const that = this
    const category = 'poetry'
    const dynasty = this.data.selectedDynasty
    const search = this.data.searchText

    this.setData({ loading: true })

    app.requestWithToken({
      url: 'http://127.0.0.1:8056/index.php?c=api&a=getCategoryContent',
      method: 'GET',
      data: {
        category,
        dynasty,
        search,
        page: 1,
        limit: 20
      },
      success(res) {
        if (res.data.code === 1) {
          // 处理内容分行显示
          const processedItems = res.data.data.items.map(item => ({
            ...item,
            contentLines: item.content ? item.content.split('\n') : []
          }));
          that.setData({
            poetryList: processedItems,
            hasMore: res.data.data.hasMore,
            loading: false
          })
        } else {
          console.error('获取诗词数据失败:', res.data.msg)
          that.setData({ loading: false })
          wx.showToast({ title: '加载失败', icon: 'none' })
        }
      },
      fail(err) {
        console.error('网络请求失败:', err)
        that.setData({ loading: false })
        wx.showToast({ title: '网络异常', icon: 'none' })
      }
    })
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({ searchText: e.detail.value })
  },

  // 执行搜索
  performSearch() {
    this.loadPoetryData()
  },

  // 选择朝代
  selectDynasty(e) {
    const dynasty = e.currentTarget.dataset.dynasty
    this.setData({ selectedDynasty: dynasty }, () => {
      this.loadPoetryData()
    })
  },

  // 前往详情页
  goToDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}&type=poetry`
    })
  },

  // 下拉加载更多
  onReachBottom() {
    if (!this.data.loading && this.data.hasMore) {
      // 实现加载更多逻辑
    }
  }
})